<?php
class Warehouse_Service_Shelf
{

	public static function getByCondition($condition=array(),$type='*',$order=array('ws_id'), $pageSize=0, $page=1)
	{ 
		$obj=new Warehouse_Model_Shelf();
		$rows= $obj->getByCondition( $condition,$type,$order, $pageSize,$page);	
		return ($rows);
	}
	
	public static function getBySearchJoinCondition($condition=array(),$type='*',$order=array(), $pageSize=0, $page=1)
	{	
		if(isset($condition["product_sku"]) && $condition["product_sku"]!=''){
			$arrCon=explode('-',$condition['product_sku']);
			if(count($arrCon)>1){
				$condition['customer_id']=$arrCon[0];
				$condition['product_sku']=$arrCon[1];
				if($condition["product_sku"]!='' &&  $condition['customer_id']!=''){
					$modelProduct = new Product_Model_Product();
					$row = $modelProduct->getByCustomerIdAndSku($condition['customer_id'],$condition["product_sku"]);
					if(empty($row)){
						$condition['product_id']='0';
					}else{
						$condition['product_id']=$row['product_id'];
					}
				}
			}else{
				$condition['product_id']='0';
			}
		}
		$obj=new Warehouse_Model_Shelf();
		$rows= $obj->getByJoinCondition( $condition,$type,$order, $pageSize,$page);	
		return ($rows);
	}
	
	public static function getByJoinCondition($condition=array(),$type='*',$order=array(), $pageSize=0, $page=1)
	{ 
		$obj=new Warehouse_Model_Shelf();
		$rows= $obj->getByJoinCondition( $condition,$type,$order, $pageSize,$page);	
		return ($rows);
	}
	
	public static function getByJoinChooseCondition($condition=array(),$type='*',$order=array(), $pageSize=0, $page=1)
	{ 
		$povServiceObj = new Product_Model_ProductOptionValue();
		$category = $povServiceObj->getByProductId($condition['product_id'],1)->current();
		if($category instanceof Zend_Db_Table_Row){
			$category = $category->toArray();
			$condition['poc_id']=$category['poc_id'];
		}
		if(!isset($condition["status"])){
			$condition["status"]='1';
        }
		if(!isset($condition["wa_type"])){
			$condition["wa_type"]='1';
        }
		$obj=new Warehouse_Model_Shelf();
        /*随机*/
        if(isset($condition["rand"]) && $condition["rand"]!='' ){
            $randRow=$obj->getByRandShelf();
            $condition["rand"]=$randRow['ws_id'];
        }

		$rows= $obj->getByJoinChooseCondition( $condition,$type,$order, $pageSize,$page);	
		return ($rows);
	}

	public static function getByfield($field,$value)
	{ 
		$obj=new Warehouse_Model_Shelf();
		$rows= $obj->getByfield($field,$value);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}

    public static function getBySortInWscode($wscode,$type='*',$orderby=array('ws_sort desc'))
    {
        $obj=new Warehouse_Model_Shelf();
        $rows= $obj->getBySortInWscode($wscode,$type,$orderby);
        return $rows;
    }
	
	public static function getById($t_id)
	{ 
		$obj=new Warehouse_Model_Shelf();
		$rows=$obj->getById($t_id);
		if(!empty($rows)){
			$rows=$rows->toArray();
		}
		return $rows;
	}
	


	public static function create($row)
	{ 
		$obj=new Warehouse_Model_Shelf();
		return $obj->create($row);
	}

	public static function update($row,$t_id)
	{ 
		$obj=new Warehouse_Model_Shelf();
		return $obj->update($row,$t_id);
	}	
	
	/**
	*根据分区CODE，级联修改wh_status
	*@param string $wa_code, 
	*/
	public static function updateStatus($wa_code,$status)
	{ 
		$updateRow=array(
			'ws_statu'=>$status
		);
		$obj=new Warehouse_Model_Shelf();
		$obj->updateByWaCode($updateRow,$wa_code);
	}	
	
	public static function delete($id)
	{ 
		$obj=new Warehouse_Model_Shelf();
		return $obj->delete($id);
	}

	public static function getIP()
	{ 
		$ip=$_SERVER['REMOTE_ADDR'];
		return $ip;
	}
	
    public static function validator($val) {
        $error = array();
        $validateArr = array();
		if(!isset($val['ws_id']) || $val['ws_id']==''){
            $validateArr[] = array('name' => '仓库', 'value' => $val['warehouse_id'], 'regex' => array('require', 'positive1', ));
			$validateArr[] = array('name' => '房间号', 'value' => $val['wh_code'], 'regex' => array('require', 'length[0,255]', ));
			$validateArr[] = array('name' => '货架号', 'value' => $val['ws_code'], 'regex' => array('require', 'length[3,25]','euexp_char','en_char', ));
			$validateArr[] = array('name' => '仓库区域', 'value' => $val['wa_code'], 'regex' => array('require', 'length[0,255]', ));
		}

		$validateArr[] = array('name' => '货架类型', 'value' => $val['wsc_code'], 'regex' => array('require', 'length[0,255]', ));
        $validateArr[] = array('name' => '优先级', 'value' => $val['ws_sort'], 'regex' => array('require', 'number[0,1000]', ));
        $error = Common_Service_Validator::formValidator($validateArr);
        return $error;
    }
	/*
	*验证批量创建货架号表单数据
	*/
    public static function batchvalidator($val) {
        $error = array();
        $validateArr = array();
        $validateArr[] = array('name' => '仓库', 'value' => $val['warehouse_id'], 'regex' => array('require', 'positive1', ));
        $validateArr[] = array('name' => '房间号', 'value' => $val['wh_code'], 'regex' => array('require', 'length[0,255]', ));
        $validateArr[] = array('name' => '仓库区域', 'value' => $val['wa_code'], 'regex' => array('require', 'length[0,255]', ));
		$validateArr[] = array('name' => '货架类型', 'value' => $val['wsc_code'], 'regex' => array('require', 'length[0,255]', ));
        $validateArr[] = array('name' => '货架起始编号', 'value' => $val['begin_label'], 'regex' => array('require', 'length[0,255]','en_char', ));
        $validateArr[] = array('name' => '货架结束编号', 'value' => $val['end_label'], 'regex' => array('require', 'length[0,255]','en_char', ));
        $validateArr[] = array('name' => '货架起始列', 'value' => $val['begin_column'], 'regex' => array('require', 'length[0,255]','english', ));
        $validateArr[] = array('name' => '货架起始列', 'value' => $val['end_column'], 'regex' => array('require', 'length[0,255]','english', ));
        $validateArr[] = array('name' => '货架起始行', 'value' =>$val['begin_row'], 'regex' => array('require','integer', ));
        $validateArr[] = array('name' => '货架结束行', 'value' =>$val['end_row'], 'regex' => array('require','integer', ));
        $validateArr[] = array('name' => '优先级', 'value' => $val['ws_sort'], 'regex' => array('require', 'number[0,1000]', ));
        $error = Common_Service_Validator::formValidator($validateArr);
        return $error;
    }
	/**
	*获取产品目录
	*/
	public static function getProductOptionChoose($poId=1)
	{ 
		$obj=new Product_Model_ProductOptionChoose();
		return $obj->getAllByOption($poId)->toArray();
	}	
	
	/**
	*获取货架类型
	*/
	public static function getShelfClass($condition=array())
	{ 
		$obj=new Warehouse_Model_ShelfClass();
		return $obj->getByCondition($condition);
	}
	
	public static function log($wpId,$wsCode,$warehouseId=1){
		$date=date("Y-m-d:H:i:s");
		$row = array("wp_status"=>0);
			
		if(!Warehouse_Service_Products::update($row, $wpId)){
		
			$result[]=array(
					"msg"=>'update['.$wsCode.'] status failure',
					'time'=>$date,
					"ask"=>0
			);
		
		}else{
			//货架使用日志
			$WarehouseProductsLog = array(
					'wpl_refId' => 'reclaimShelf',
					'user_id' =>'0',
					'warehouse_id' => $warehouseId,
					'ws_code' => $wsCode,
					'wpl_proc_type' => 4, //状态修改
					'wpl_note' => 'auto reclaim shelf',
					'wpl_add_time'=>$date
			);
		
			if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
		
				$result[]=array(
						"msg"=>'update['.$wsCode.']failure',
						'time'=>$date,
						"ask"=>0
		
				);
			}else{
				$result[]=array(
						"msg"=>'update['.$wsCode.']status form 1 to 0，succeed!',
						'time'=>$date,
						"ask"=>0
				);
					
			}
		}
	}

	/**
	 * 回收货架号
	 */
	public  static function reclaimShelf(){
		$date=date("Y-m-d:H:i:s");
		$condition=array(
				'wp_quantity' =>'0',
				'wp_quantity_hold'=>'0',
				'wp_status'=>1
				);
		
		$wpRows=Warehouse_Service_Products::getByConditionAll($condition);
		//print_r($wpRows);exit;
		
		$result=array();
		
		$filed=array('orders_code', 'orders_status', 'process_status');
		
		foreach ($wpRows as $wp){
			
			//如果是正在盘点
			if($wp['wp_status']==2){
				continue;
			}
			
			//先判断总库存Hold是否为0
			$productStocket = Product_Service_ProductStocket::getByProductId($wp['product_id'],$wp['warehouse_id']);
			if(!isset($productStocket['ps_quantity_hold']) ||  $productStocket['ps_quantity_hold']==0){
				 
				self::log($wp['wp_id'],$wp['ws_code'],$wp['warehouse_id']);
				continue;
			}
			

			$opCondition=array('product_id' => $wp['product_id']);
			$orderProduct = Order_Service_Product::getByCondition($opCondition, 'orders_code', array('op_id desc'), 0, 0);
			
			if(!$orderProduct){
	
				self::log($wp['wp_id'],$wp['ws_code'],$wp['warehouse_id']);
				
				continue;
			}
	
			foreach ($orderProduct as $key => $val) {
				
				$orders = Order_Service_Order::getByValue($val['orders_code'], 'orders_code',$filed );
				if (isset($orders['orders_code']) && $orders['process_status'] < 5 && $orders['process_status'] > 1) {
					$opmModel = new Order_Model_OrderPickupMap();
					$orderPickupMap = $opmModel->getByfield('orders_code', $orders['orders_code']);
					foreach ($orderPickupMap as $k => $v) {
						$wpbRow = Warehouse_Service_ProductsBatch::getById($v['wpb_id']);
						//如果有订单关联，返回状态不可修改
						if ($wpbRow['warehouse_id'] == $wp['warehouse_id'] && $wpbRow['product_id'] == $wp['product_id'] && $wpbRow['ws_code'] == $wp['ws_code']) {
			              continue 3;
							//有相关的,不能更改状态
							
						}else{
							
							//如果是正在盘点
							if($wp['wp_status']==2){
								continue 3;
							}

							self::log($wp['wp_id'],$wp['ws_code'],$wp['warehouse_id']);
							continue 3;
						}
					}
				}
			}
			
		}

		//throw new Exception("不存在相关订单");
		return $result;
		
	}

    /*
     * warehouse_shelf left join warehouse_products
     */
    public static function getByLeftJoinWarehouseProductsCondition($condition=array(),$type='*', $pageSize=0, $page=1,$orderBy=array())
    {
        $obj=new Warehouse_Model_Shelf();
        //默认为可用
        if(!isset($condition["ws_statu"])){
            $condition["ws_statu"]='1';
        }
        /*随机*/
        if(isset($condition["rand"]) && $condition["rand"]!='' ){
            $randRow=$obj->getByRandShelf(array('wa_code'=>isset($condition['wa_code'])?$condition['wa_code']:''));
            $condition["rand"]=$randRow['ws_id'];
        }
        $rows= $obj->getByLeftJoinWarehouseProductsCondition( $condition,$type, $pageSize,$page,$orderBy);
        return ($rows);
    }

}